package cn.rengy.web.framework.wxmp;

import java.util.Map;
import java.util.concurrent.Callable;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.rengy.web.framework.cache.CacheService;
import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.sys.pub.upload.service.PubFileService;

@Service
public class WxAppService {
	@Autowired
	private DbService dbService;
	private static Logger logger = LoggerFactory.getLogger(WxAppService.class);
	@Autowired
	CacheManager cacheManager;
	@Autowired
	private PubFileService pubFileService;
	
	@Autowired
	private CacheService cacheService;
	
	/**
	 * 更新欢迎信息
	 * @param param
	 */
	public void updateWelcomeMsg(Map<String,Object> param) {
		String appid=MapUtils.getString(param, "appid");
		String welcome_msg=MapUtils.getString(param, "welcome_msg");
		this.dbService.update("update_wx_app_welcome_msg",welcome_msg,appid);
		cacheService.evict("wxAppCache", appid);
	}
	
	
	public WxApp getApp(String appid){
		
		return cacheService.getCache("wxAppCache", appid, new Callable<WxApp>() {
	        @Override
	        public WxApp call() throws Exception {
	        	return dbService.queryForBean("select_get_wx_account",WxApp.class, appid);
	        }
	    });
		
	}
	@Transactional(rollbackFor=Exception.class)
	public void delete(Long wx_account_id){
		Map<String,Object> account=this.dbService.queryForMap("select_get_wx_account_byid", wx_account_id);
		Long apiclient_cert=(Long)account.get("apiclient_cert");
		Long qrcode_fileid=(Long)account.get("qrcode_fileid");
		//1.删除证书
		if(apiclient_cert!=null){
			pubFileService.realDeleteById(apiclient_cert);	
		}
		//2.删除二维码
		if(qrcode_fileid!=null){
			pubFileService.realDeleteById(qrcode_fileid);
		}
		//3.删除账号
		this.dbService.updateBeanParameter("delete_wx_account", wx_account_id);
	}
	/**
	 * 
	 * @param wx_account
	 * @return
	 * @throws Exception
	 */
	public Long save(Map<String,Object> wx_account) {
		String id=MapUtils.getString(wx_account, "id");
		if(id==null){//新增
			this.dbService.updateMapParameter("insert_wx_account", wx_account);
		}else{//修改
			this.dbService.updateMapParameter("update_my_wx_account", wx_account);
		}
		//二维码不删除
		return null;
	}
}
